#include "ClientBootstrap.h"
#include "Connector.h"
#include "Log.h"

namespace dsth {

ClientBootstrap::ClientBootstrap(EventLoop* loop, const InetSocketAddress& server_addr,  const char* name)
    :loop_(loop),
    connector_(new Connector(loop, server_addr)),
    name_(name),
    conn_ptr_(NULL) {
    connector_->SetConnectHandler(std::make_pair(this, &ClientBootstrap::OnNewConnection));
    connector_->SetConnectRefusedHandler(std::make_pair(this, &ClientBootstrap::OnRefused));
}


ClientBootstrap::~ClientBootstrap(void) {
    LOG_DEBUG("[ClientBootstrap::~ClientBootstrap] name:%s.", name_.c_str());
}

void ClientBootstrap::Connect() {
    connector_->Connect();
}

void ClientBootstrap::Disconnect() {
    if (conn_ptr_.get()) {
        conn_ptr_->ShutDown();
    }
}

void ClientBootstrap::OnNewConnection(int fd) {
    InetSocketAddress local_addr(net::GetHostAddr(fd));
    InetSocketAddress peer_addr(net::GetPeerAddr(fd));

    LOG_DEBUG("[ClientBootstrap::OnNewConnection] local addr=%s, peer addr=%s", 
        local_addr.ToHostPortFormat().c_str(), peer_addr.ToHostPortFormat().c_str());
    conn_ptr_.reset(new Connection(loop_, 0, fd, local_addr, peer_addr));
    conn_ptr_->SetConnectionHandler(conn_handler_);
    conn_ptr_->SetMessageHandler(msg_handler_);
    loop_->RunInLoop(std::make_pair(conn_ptr_.get(), &Connection::ConnectEstablished));
}

void ClientBootstrap::OnCloseConnection(Connection* conn) {
    dis_conn_handler_(conn);
}

void ClientBootstrap::OnRefused() {
    refused_handler_();
}

} // namespace
